package com.zdb.util;

import cn.hutool.core.util.IdUtil;
import com.zdb.common.Constant;
import com.zdb.pojo.LoginUser;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Component
    public class JwtUtil {

    private static final Logger log = LoggerFactory.getLogger(JwtUtil.class);
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;
    @Autowired
    private RedisTemplate redisTemplate;

    public String createToken(LoginUser loginUser){
        String uuid = IdUtil.fastUUID();
        setCache(loginUser,uuid);
        return buildToken(loginUser,uuid);
    }

    public void setCache(LoginUser loginUser,String uuid){
        redisTemplate.opsForValue().set(Constant.USER_KEY+uuid,loginUser,expiration, TimeUnit.MINUTES);
    }

    public String buildToken(LoginUser loginUser,String uuid){
        HashMap<String, Object> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put(Constant.USER_KEY,uuid);
        stringStringHashMap.put("username",loginUser.getUsername());
        return Jwts.builder()
                .setClaims(stringStringHashMap)
                .signWith(SignatureAlgorithm.HS512,secret)
                .setExpiration(new java.util.Date(System.currentTimeMillis() + expiration *60 * 1000))
                .compact();
    }
    public void delToken(String token){
        Claims claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        redisTemplate.delete(Constant.USER_KEY+claims.get(Constant.USER_KEY));
    }
    public LoginUser getLoginUser(String  token){
        LoginUser loginUser = null;
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
            String userKey = (String)claims.get(Constant.USER_KEY);
            loginUser = (LoginUser) redisTemplate.opsForValue().get(Constant.USER_KEY + userKey);
            if (loginUser != null) {
                loginUser.setAuthorities(loginUser.getAuthorities());
            }
        } catch (Exception e) {
            log.error("获取用户信息异常:{}",e.getMessage());
        }
//        LoginUser loginUser = JSON.parseObject((String) redisTemplate.opsForValue().get(Constant.USER_KEY + userKey), LoginUser.class);
        return loginUser;
    }
//    public String parseUsernameByToken(String token){
//        return  Jwts.parser()
//                .setSigningKey(secret)
//                .parseClaimsJws(token)
//                .getBody()
//                .getSubject();
//    }

}
